Skip to content

server: streams of frames and moving bytes by reference (frame_ring, buffer_ref, memory_mover) — host-pool slice 1 - #134

Open
joelteply wants to merge 7 commits into
codex/s4-per-mind-integrationfrom
fable/frames-s4
Open

joelteply wants to merge 7 commits into
codex/s4-per-mind-integrationfrom
fable/frames-s4

Conversation

@joelteply

Copy link
Copy Markdown

First slice of the unmerged fable/host-pool work, onto the shipping line. It is the substrate for Joel's direction (2026-11-16): dynamic stream-based allocation with typed ids and handles, instead of the prompt cache's prefix matching and refuse/drop decisions (CONTINUUM-ENGINE 4.7.12).

What it adds (header-only, no call sites yet)

  • frame_ring<T>: a lock-free single-producer/single-consumer ring of trivially copyable frames (ids and references, never payloads).
    • A full ring is backpressure the producer sees at once.
    • An empty ring sleeps the consumer on an atomic wait (a futex), never a lock, timer or promise.
  • buffer_ref: bytes named (domain, pool, buffer id, offset, length), never carried.
  • memory_mover: the one base for moving bytes between domains.
    • It takes transfer frames in and gives completion frames out; a backend implements only start.
    • Moves run in parallel across lanes and chunks, and pump never waits.
    • Within one physical domain (unified memory) a move is a new reference, not a copy.
  • Copy lanes: the node's efficiency-core count is the first guess, read from the OS. measure_copy_lanes confirms the knee at startup.

Changes from the original commits

Cherry-picked with -x (0a5a1df, 5f22d26, 64fb163, 92796c6). The test is compiled as C++20 (the server's standard since #129) instead of C++23; no C++23 feature is used.

Measured (M5, 2026-11-16)

  • test-server-frames: ok, model-free.
  • The same test under ThreadSanitizer (clang, -O1): ok, 0 reports.
  • From the original commit: 12 lanes = 118.9 GB/s on the M5 Pro's 12 E-cores.
  • 0 warnings.

Next slices

  1. The job system (engine_module).
  2. Host bytes and the host pool (one budget across prompt cache, checkpoints and pages).
  3. Device snapshots and pages saved off the main thread.
  4. Parked checkpoints.
  5. The step frame.

The prompt cache's disk tier (#124) is then replaced by pages keyed by id, under the host pool.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

joelteply and others added 4 commits November 16, 2026 13:15
…ce (frame_ring, buffer_ref, memory_mover)

Joel 2026-11-16: "Fast tokenless memory transfer and DMA must be encoded into a pattern or parent
class, reused"; "Streaming not promises"; "pass references and ids ... do in parallel, don't wait."

- frame_ring<T>: lock-free single-producer/single-consumer ring of frames; T must be trivially
  copyable (ids, references, counters, never a payload with an owner). Fixed power-of-two capacity
  allocated once. A full ring is backpressure the producer sees at once; wait_for_room / wait_for_frames
  are atomic waits (futex), never a lock, timer or promise. The closed flag is the top bit of the tail
  word, because an atomic wait returns only when its word changes (a first version kept it separate
  and a closing producer never woke the consumer; found by the validator hanging).
- buffer_ref: bytes named, never carried (domain, pool, buffer, offset, length).
- memory_mover: the one base for every byte mover. It drains a stream of transfer frames and starts
  each on its backend's own engine without waiting; a move within one physical domain is ALIASED
  (nothing copied); an unsupported pair is REFUSED typed (never a silent CPU copy). Completions come
  from two producers, each with its own SPSC ring (the pumping thread settles aliased/refused, the
  backend's completion context finishes moves) and one doorbell counter wakes the consumer: lock-free
  fan-in. (A first version shared one ring between both producers; ThreadSanitizer caught the race.)
  A backend implements only start() and aliases().

test-server-frames: 2,000,000 frames through a 64-slot ring in order; 8 rings x 250,000 frames at
once; backpressure; close wakes a sleeping consumer; 900 transfers (moved on the engine, aliased,
refused) streamed back exactly once from two producers. ok 3x under TSan (no reports) and 3x under
ASan/UBSan; 0 warnings from the cmake build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit 0a5a1df)
…etion rings) and pump never waits

Joel 2026-11-16: "Memory transfer is usually not a serial system though. Remember DMA and that we
have 20 cores?" The first memory_mover had one pump and one completion context.

- memory_mover: N completion contexts (lanes: CPU copy threads, GPU blit queues, disk readers), each
  completing into its own SPSC ring, plus the pump's settled ring; one doorbell fans them in. pump()
  starts what the engines have room for and RETURNS (start_result::would_block keeps the transfer
  pending, the backend remembers its progress, the next pump resumes); the caller drains completions
  in between. A first parallel version blocked inside pump on a full lane ring while the lanes
  blocked publishing completions the same thread had to drain: a deadlock the validator exposed.
- parallel_copier (host backend): a transfer splits into chunks round-robin across lanes, many
  transfers in flight (bounded by owner-sized in-flight slots), the LAST chunk to land publishes the
  completion; size mismatches and disk pairs refused typed. Lane count and chunk size are inputs from
  the node's measured copy curve.

Measured on this M5 Pro (18 cores: 6P + 12E, live engine sharing the machine): plain memcpy 1 GiB
61 GB/s on 1 thread, 116 on 8, 119 on 12, 109 on 18. parallel_copier, 16 x 64 MiB transfers, 4 MiB
chunks: 1 lane 39.1 GB/s, 4 lanes 83.5, 8 lanes 98.0, 12 lanes 118.9 (3.0x). test-server-frames ok
3x under TSan and 3x under ASan/UBSan (200 x 1 MiB through 6 lanes byte-exact, every ticket once);
0 warnings from the cmake build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit 5f22d26)
…count (Joel; matches the measured knee: 12 lanes = 118.9 GB/s on the M5 Pro's 12 E-cores), read from the OS, refined by measurement

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit 64fb163)
…tartup, holding to the efficiency-core guess against noise

Joel: "your first guess should be near the number of efficiency cores." The guess (efficiency_cores())
is then MEASURED on the node: copy a probe buffer with the guess and a few neighbors (best of three
each) and keep the guess unless another count beats it by more than the caller's margin. A first
version kept the smallest count within 95% of the best and flipped between 12 and 16 lanes run to
run on the M5 (the live engine shares the machine; observed spread 94.7-117.9 GB/s, about +-10%), so
the margin is hysteresis toward the guess: noise never moves the choice, a real knee elsewhere does.

Receipt, M5 Pro (12 E-cores), margin 0.90, 256 MiB probe, candidates 6/8/12/16/18: 12 lanes on 5 of 5
runs at 94.7-113.6 GB/s; the probe takes 65-84 ms, once at startup, off the decode thread.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit 92796c6)
@joelteply

Copy link
Copy Markdown
Author

Independent source review exact0dffc1014f59a8a765f6da0c6a96c78da61f92e2: BLOCK.

P1: pump synchronously publishes aliases/refusals into settled completion ring; full ring sleeps although same caller drains only after pump returns. Capacity2 plus3 aliases deadlocks. Preserve pending completion and return bounded backpressure.
P1: destructor closes work rings then joins workers blocked on full completion rings, with no completion cancel/drain/wake protocol. Define terminal outcomes for outstanding tickets and unblock publishers.
P2: alias shortcut succeeds before validating lengths/resolver/buffer references; same ID/offset with unequal lengths or stale IDs can falsely succeed.
P1: overlapping ranges in same buffer reach parallel memcpy; UB/races. Refuse overlap or an explicitly ordered overlap-safe operation, not independent chunk memmoves.

Custody must be explicit before integration: buffer_ref lacks generation, resolver returns raw pointers and queued chunks retain no pool lease/admission receipt. Define external owner lifetime/reuse/bounds contract. Test completion saturation, outstanding teardown, invalid alias, overlap. TSan receipt is owner-reported, not visible CI. Reviewer checkpoint_close_review; no builds performed.

…cket ends once, aliases and overlaps validated; buffer refs carry a generation (Codex's review of #134)

- pump: a settlement that does not fit the settled ring is held for the caller's drain (same thread) and pump
  takes nothing new until it drains: bounded backpressure, never a sleep inside pump (capacity 2 + 3 aliases
  deadlocked).
- Completions are bounded by slots: a copier slot is retired only when its completion is DRAINED, and every
  lane's ring holds every slot, so a lane's push can never find its ring full (a broken bound aborts loudly;
  it is never a wait). The destructor no longer joins lanes blocked on completion.
- shutdown(): every transfer queued or pending that no lane holds is settled `cancelled` (nothing written);
  one part-handed ends once, `failed` (a partial destination) from its last landed chunk; after it every
  pushed ticket has exactly one terminal frame, and the closed ring takes nothing more.
- buffer_ref.generation + the custody contract (the owning pool keeps a buffer live and unrecycled until its
  transfer's completion is drained; the resolver refuses a stale generation, an unknown buffer or bytes out
  of bounds). An alias requires equal generation, offset AND length and a resolved reference.
- Overlapping ranges in one buffer are refused (independent parallel chunks over them race: UB).

Tests (one regression each): a full completion ring is backpressure, not a deadlock; unequal-length and
stale-generation aliases, overlap and out-of-bounds refused while a disjoint copy in one buffer moves;
teardown with 64 transfers outstanding on two slots ends every ticket (moved/failed/cancelled, some
cancelled) and the destructor joins. Receipt (M5): test-server-frames ok; under -fsanitize=thread 5 of 5
runs ok with 0 reports; under -fsanitize=address,undefined ok. -Wall -Wextra -Werror.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
@joelteply

Copy link
Copy Markdown
Author

Re-review exact95843948d930d3efcae21383c4dbdfa42eec6f54: BLOCK.
Prior completion-ring deadlocks and same-ID aliases/overlaps addressed.
P1: retained custody remains a caller comment/raw-pointer resolver; no owner-issued pin/lease/admission covering source/destination through queued chunks and terminal drain. Generation at resolution does not prevent subsequent reuse. Implement retained resolution through existing pool owner and prove attempted reuse/free while paused; no separate ownership system.
P1: shutdown closes input from consumer while push publishes tail.store(old_tail+1); producer paused after reading old tail can erase CLOSED, publish after drain and strand a ticket. wait_for_room also has no closed terminal result and treats closed flag in occupancy. Need producer closure coordination/close-safe publish and close-aware waits. Test paused publication racingclose and full-ring producer shutdown.
Distinct logical IDs resolving overlapping physical memory also bypass ID-only overlap checks; require canonical allocation identity or validate resolved spans.
Reviewer checkpoint_close_review; exactCIpending and owner sanitizers do not exercise these cases.

…the owning pool's pins are held until drain; alias and overlap are decided on physical ranges (Codex's second review of #134)

- frame_ring: push publishes by CAS on the tail word, so a frame is accepted iff it lands before a close;
  the closed bit lives on BOTH words (head advances by fetch_add, close is fetch_or), so neither side's
  update erases it; wait_for_room wakes on close and returns false.
- buffer_pin: the owning pool's custody of a resolved reference (address + the pool's own unpin, RAII,
  move-only). parallel_copier<Resolver> takes a resolver returning pins (no std::function), holds a transfer's
  src and dst pins in its slot from start until its completion is DRAINED, and returns them on cancel paths.
  Nothing new owns memory: the pool does.
- Aliasing and overlap are decided on the resolved PHYSICAL ranges: the same address is `aliased` (pins
  returned at once), any other overlap is refused, so two ids naming the same bytes are caught.

Tests: a close racing a producer (2,000 rounds): the closed bit survives and every push that returned true is
drained; a transfer holds both pins after its completion is published and returns them only on drain; two ids
over the same bytes alias, over overlapping bytes are refused; every test pool ends with 0 pins out.
Receipt (M5): test-server-frames ok; -Wall -Wextra -Werror under -fsanitize=thread 5 of 5 ok, under
-fsanitize=address,undefined ok.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
@joelteply

Copy link
Copy Markdown
Author

Re-review134 exactf8d694f89281b11453ebcafac2dc1d42825a78f9 BLOCK: alias start destroys localpins before terminaldrain; cancel_pending free_slot likewiseearly when allhandedchunkslanded. Retain terminalslot/pins throughdrain forimmediatealias andpartcancel too. Tests mustholdpins beforedrain and releaseexactlyonceafter. PriorcloseCAS/copycustody/physicalaliasfixesresolved. Reviewer checkpoint_close_review.

…ained, aliases and late cancels included (Codex's third review of #134)

- An alias claims a slot and holds both pins there; it settles `aliased` with that slot, so the pins return
  only when the frame is drained (they were returned at once).
- cancel_pending keeps the slot (and its pins) for a transfer cancelled with nothing handed, or whose handed
  chunks had all landed: the base settles that terminal with the slot (terminal_slot_), retired on drain.
- Overlap still refused, now checked before the slot claim; equal addresses are the alias.

Test: an alias across two ids over the same bytes holds both pins after it settles and returns them only on
drain. Receipt (M5): test-server-frames ok; -Wall -Wextra -Werror under -fsanitize=thread 5 of 5 ok, under
-fsanitize=address,undefined 3 of 3 ok.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
@joelteply

Copy link
Copy Markdown
Author

Independent checkpoint_close_review APPROVE source exact2042f0d62e16880c317c058707811749d688dd4d conditional exactCI. Alias/no-chunk/already-landed cancellation retainpins interminalslotuntildrain; partialremainingcount choosesexactlyoneterminalpublisher; priorclose/backpressure/physicaloverlap fixesintact. Aliasregressioncoverspinretention. Deterministicbothpartialcanceloutcomes coveragewouldstrengthen. Owner sanitizerreceiptsnotindependentCI; no builds.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant